import { defineStore } from 'pinia'
import { articleApi } from '@/api/article'

export const useArticleStore = defineStore('article', {
    state: () => ({
        articles: [],
        latestArticles: [],
        popularArticles: [],
        searchResults: [],
        tags: [],
        currentArticle: null,
        relatedArticles: null,
        loading: false,
        total: 0,
        count: 0
    }),

    actions: {
        async fetchArticles(page = 1, pageSize = 10, category) {
            try {
                this.loading = true
                const response = await articleApi.getArticles( (page-1), pageSize, category)
                this.articles = response.content
                this.total = response.totalElements
            } finally {
                this.loading = false
            }
        },

        async fetchArticle(id) {
            try {
                this.loading = true
                const response = await articleApi.getArticle(id)
                this.currentArticle = response.data.article
                this.relatedArticles = response.data.relatedArticles
                this.count = response.data.article.viewCount
                this.tags = response.data.article.tags
            } finally {
                this.loading = false
            }
        },

        async fetchLatestArticles() {
            try {
                this.loading = true
                const response = await articleApi.getLatestArticles()
                this.latestArticles = response.content
            } finally {
                this.loading = false
            }
        },

        async fetchPopularArticles() {
            try {
                this.loading = true
                const response = await articleApi.getPopularArticles()
                this.popularArticles = response.content
            } finally {
                this.loading = false
            }
        },

        async searchArticles(keyword,currentPage,pageSize) {
            try {
                this.loading = true
                const response = await articleApi.searchArticles(keyword,currentPage,pageSize)
                this.searchResults = response.items
                this.total = response.total
            } finally {
                this.loading = false
            }
        }
    }
})
